const { queryCompanyOptions } = require("../../../api/company");
const { queryAllArea } = require("../../../api/area");
const { queryDeptOptions } = require("../../../api/dept");
const { queryAllAssetsType } = require("../../../api/assetsType");
const { addAssets, updAssets } = require("../../../api/assets");
const { clearEmptyKey } = require("../../../utils/clearEmptyKey");

const {
  getEventData,
  routeWithToken,
  to,
  showToast,
  openLoading,
  closeLoading,
  backParentLoad,
} = getApp();
Page({
  data: {
    assetsTypeOptions: [],
    companyOptions: [],
    areaOptions: [],
    deptOptions: [],
    pickerShow: {
      deviceTypeVisible: false,
      unitVisible: false,
      areaVisible: false,
      userNameVisible: false,
    },
    formData: {
      assetsTypeId: "",
      companyId: "",
      areaId: "",
      assetsName: "",
      assetsSerialNumber: "",
      operationsDepartment: "",
      comments: "",
      userIds: "",
      departmentId: "",
      assetsPropsVOS: [],
    },
    formType: "",
    isReady: false,
    isScan: ''
  },

  onLoad() {
    this.getAllPickerOptions();
    this.setData({
      isScan: this.options.isscan
    })
  },

  async getAllPickerOptions() {
    this.setData({
      isReady: false,
    });
    const { type } = this.options;
    this.setData({
      formType: type,
    });
    let optionsData;
    this.getFormDataByType();

    const dataItem = wx.getStorageSync('device-manager')
    if (dataItem) {
      optionsData = JSON.parse(dataItem);
    }

    wx.setStorageSync('device-manager', null)
    openLoading();
    await to(
      Promise.all([
        this.getAllArea(),
        this.getCompanyList(),
        this.getQueryAllAssetsType(),
      ])
    );

    if (optionsData) {
      this.setData({
        ["formData.companyId"]: optionsData.companyId,
      });

      this.getPromiseByCompany(false).then(() => {
        closeLoading();
        this.setData({
          formData: optionsData,
          isReady: true,
        });
      });
    } else {
      closeLoading();
      this.setData({
        isReady: true,
      });
    }
  },

  async getPromiseByCompany(openLoad = true) {
    openLoad && openLoading();
    const [err] = await to(this.getQueryDeptOptions());
    closeLoading();

    if (!err) {
      return Promise.resolve();
    }
    return Promise.reject();
  },

  async getQueryDeptOptions() {
    const { companyId } = this.data.formData;
    const [err, data] = await to(
      queryDeptOptions({
        companyId: companyId,
      })
    );

    if (!err) {
      this.setData({
        deptOptions: data,
      });
      return Promise.resolve();
    }
    return Promise.reject();
  },

  async getAllArea() {
    const [err, data] = await to(queryAllArea({}));

    if (!err) {
      this.setData({
        areaOptions: data,
      });
      return Promise.resolve();
    }
    return Promise.reject();
  },

  async getCompanyList() {
    const [err, data] = await to(queryCompanyOptions({}));

    if (!err) {
      this.setData({
        companyOptions: data,
      });
      return Promise.resolve();
    }
    return Promise.reject();
  },

  async getQueryAllAssetsType() {
    const [err, data] = await to(queryAllAssetsType({}));

    if (!err) {
      this.setData({
        assetsTypeOptions: data,
      });
      return Promise.resolve();
    }
    return Promise.reject();
  },

  onCustomFormTypeChange(event) {
    const { type } = getEventData(event);
    this.setData({
      [`formData.${type}`]: event.detail,
    });

    this.clearForm(type);
    if (type === "assetsTypeId") {
      const item = this.data.assetsTypeOptions.find(
        (item) => item.assetsTypeId === event.detail
      );

      if (item) {
        const propVOS = item.assetsPropsVOS;
        this.setData({
          ["formData.assetsPropsVOS"]: propVOS.map((m) => {
            m.propValue = "";
            return m;
          }),
        });
      }
    }
    if (type === "companyId") {
      if (event.detail || event.detail === 0) {
        this.getPromiseByCompany();
      }
    }
  },

  clearForm(type) {
    let clearList = [];
    let optionsList = [];
    if (type === "assetsTypeId") {
      clearList = ["assetsPropsVOS"];
    }

    if (type === "companyId") {
      clearList = ["departmentId", "userIds", 'userNames'];
      optionsList = ["deptOptions"];
    }

    for (const item of clearList) {
      this.setData({
        [`formData.${item}`]: "",
      });
    }

    for (const item of optionsList) {
      this.setData({
        [item]: [],
      });
    }
  },

  onAssetsPropVOSChange(event) {
    const { index } = getEventData(event);
    this.setData({
      [`formData.assetsPropsVOS[${index}].propValue`]: event.detail,
    });
  },

  onUserIdsClear() {
    this.setData({
      ["formData.userIds"]: [],
      ["formData.userNames"]: '',
    });
  },

  async getFormDataByType() {
    const { formType } = this.data;
    let title = "设备录入";
    if (formType === "review") {
      title = "设备详情";
    } else if (formType === "edit") {
      title = "设备修改";
    }
    wx.setNavigationBarTitle({
      title,
    });
  },

  handleSubmit() {
    const result = this.checkFormData();

    if (result) {
      this.saveData();
    }
  },

  async saveData() {
    const { formData } = this.data;
    const params = {
      assetsTypeId: formData.assetsTypeId,
      companyId: formData.companyId,
      areaId: formData.areaId,
      assetsName: formData.assetsName,
      userIds: formData.userIds,
      assetsSerialNumber: formData.assetsSerialNumber,
      operationsDepartment: formData.operationsDepartment,
      comments: formData.comments,
      assetsPropsVOS: JSON.stringify(formData.assetsPropsVOS),
      assetsId: formData.assetsId,
      departmentId: formData.departmentId,
    };
    clearEmptyKey(params);
    let apiName = addAssets;

    if (formData.assetsId || formData.assetsId === 0) {
      apiName = updAssets;
    }

    openLoading();
    const [err] = await to(apiName(params));
    closeLoading();
    if (!err) {
      showToast({
        message: "保存成功",
        type: "success",
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad();
          }, 1000);
        },
      });
    }
  },

  setUserData(data) {
    this.setData({
      ["formData.userIds"]: data.map((item) => item.userId),
      ["formData.userNames"]: data.map((item) => item.userName).join(','),
    });
  },

  checkFormData() {
    const rules = [
      "assetsTypeId",
      "companyId",
      "areaId",
      "assetsName",
      "assetsSerialNumber",
    ];
    const rulesLabel = [
      "请选择资源类型",
      "请选择公司",
      "请选择所在区域",
      "请填写资源名称",
      "请填写资源编号",
    ];
    for (const index in rules) {
      const arr = rules[index].split(".");
      const value = arr.reduce((result, key) => {
        return result[key];
      }, this.data.formData);
      if (!value && value !== 0) {
        showToast(rulesLabel[index]);
        return false;
      }
    }

    if (!this.data.formData.userIds.length) {
      showToast("请选择使用人");
      return false;
    }
    return true;
  },

  onClickChooseUsers() {
    if (!this.data.formData.companyId && this.data.formData.companyId !== 0) {
      showToast("请选择公司");
      return;
    }
    wx.navigateTo({
      url: `/page-common/choose-multiple-user/index?companyId=${this.data.formData.companyId}&departmentId=${this.data.formData.departmentId}&choosedUserIds=${JSON.stringify(this.data.formData.userIds)}`,
    });
  },

  handleToScan() {
    routeWithToken('/page-common/repair-page/index?qrCode=' + this.options.code)
  }
});
